<template>
  <!-- 图片上传 照片墙 -->
  <!-- <div class="uploadNotice" v-html="notice"></div> -->
  <div class="uploadImage">
    <el-upload
      ref="refName"
      action="#"
      v-model:file-list="fileList"
      list-type="picture-card"
      :auto-upload="false"
      :disabled="disabled"
      v-bind="attrs"
      :accept="accept"
      :on-change="handleChange"
    >
      <el-icon><Plus /></el-icon>
      <!-- 提示说明文字  -->
      <template #tip>
        <span class="ml10 upload_tip" v-if="!disabled">{{ notice }}</span>
      </template>

      <template #file="{ file }">
        <div>
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
              <el-icon><zoom-in /></el-icon>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
              <el-icon><Delete /></el-icon>
            </span>
          </span>
        </div>
      </template>
    </el-upload>
  </div>
  <el-image-viewer
    v-if="dialogVisible"
    @close="closeViewer"
    :url-list="[dialogImageUrl]"
    :zIndex="9999"
  />
</template>
<script setup>
import { ElMessage } from 'element-plus';
import { apiMethods } from '@/utils/http.js';

const props = defineProps({
  notice: {
    type: String,
    default: 'Supports png、jpeg、jpg upload, the file size does not exceed 100m',
  },
  modelValue: {
    type: Array,
    default: [],
  },
  limit: {
    type: Number,
    default: 0,
  },
  disabled: {
    // 是否禁用
    type: Boolean,
    default: false,
  },

  deleteShow: {
    // 是否展示删除按钮
    type: Boolean,
    default: true,
  },
  maxSize: {
    // 单个最大上传尺寸, 单位是M, 0为不限制
    type: Number,
    default: 0,
  },
  maxAllSize: {
    // 多个合计上传最大尺寸, 单位是M, 0为不限制
    type: Number,
    default: 0,
  },
  limit: {
    // 最大上传数量, 0为不限制
    type: Number,
    default: 0,
  },
  isRaw: {
    // 获取的file文件，还是file.row数据
    type: Boolean,
    default: true,
  },
  accept: {
    /**
     * 上传文件类型
     * xlsx: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
     * pdf: .pdf
     * docx: application/vnd.openxmlformats-officedocument.wordprocessingml.document
     * doc: application/msword
     * zip: aplication/zip
     * image: image/*(所有图片格式)，限定格式如： .png,.jpg,.jpeg.....
     * .....
     */
    type: String,
    default: '',
  },
  acceptNotice: {
    // 上传格式不符提示
    type: String,
    default: 'This transfer format is not supported',
  },
  styleC: {
    // 图片链接，可不填
    type: String,
    default: null,
  },
  deleteConfig: {
    // 删除请求接口信息
    type: Object,
    default: () => {
      return {};
    },
  },
});

const emits = defineEmits(['update:modelValue']);
let totalSize = ref(0);

const attrs = useAttrs();

const refName = ref();
let dialogImageUrl = ref('');
let dialogVisible = ref(false);

const newValue = computed({
  get() {
    init(props.modelValue);
    return props.modelValue;
  },
  set(val) {
    emits('update:modelValue', val);
  },
});

let fileList = ref(newValue);

// 初始file 数据
function init(file) {
  fileList.value = file;
}

// 预览
function handlePictureCardPreview(file) {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
}

// 删除
async function handleRemove(file) {
  let index = 0;
  const {
    requestApi = '',
    idKey = 'recid',
    axiosMethod = 'post',
    paramsArr = [],
  } = props.deleteConfig;
  fileList.value.forEach((item, itIndex) => {
    if (item.uid === file.uid || item[idKey] == file[idKey]) index = itIndex;
  });
  let row = fileList.value[index];
  if (requestApi && row[idKey]) {
    let params = {};
    params[idKey] = row[idKey];
    if (paramsArr?.length) {
      paramsArr.forEach(item => {
        if (item.definiteValue) params[item.key] = item.definiteValue;
        if (item.value) params[item.key] = row[item.value];
      });
    }
    // 调删除接口
    try {
      let res = await apiMethods[axiosMethod](requestApi, params);
      if (res.data.code || res.data.errorCode === '200') {
        ElMessage.success(res.data.msg);
        fileList.value.splice(index, 1);
        baseRef.value.init(fileList.value);
      } else {
        ElMessage.error(res.data.msg);
      }
    } catch (error) {
      console.log(error, 'errr');
    }
  } else {
    fileList.value.splice(index, 1);
  }
}
// upload change事件
function handleChange(file) {
  const maxSize = props.maxSize * 1024 * 1024;
  const maxAllSize = props.maxAllSize * 1024 * 1024;
  const { raw } = file;
  let flag = true;
  ElMessage.closeAll();
  // 附件为空，不能上传
  if (raw.size === 0) {
    ElMessage.warning(`File is empty`);
    flag = false;
  }

  // 单个不能超过最大尺寸
  if (maxSize && raw.size > maxSize) {
    ElMessage.warning(`No more than ${props.maxSize}MB`);
    flag = false;
  }

  // 多个总和不能超过最大尺寸
  if (maxAllSize && totalSize.value + raw.size > maxAllSize) {
    ElMessage.warning(`Amount No more than ${props.maxAllSize}MB`);
    flag = false;
  }

  let img = file.name.substring(file.name.lastIndexOf('.') + 1);
  const suffix = img === 'jpg';
  const suffix2 = img === 'png';
  const suffix3 = img === 'jpeg';
  if (!suffix && !suffix2 && !suffix3) {
    ElMessage.warning(props.acceptNotice);
    flag = false;
  }
  if (flag) {
    totalSize.value += raw.size;
    let len = fileList.value?.length;
    if (props.limit && props.limit <= len) fileList.value.splice(0, len + 1 - props.limit);
    raw.date = new Date();
    file.raw.date = new Date();
    fileList.value = [...(fileList.value ?? []), file];
    emits('update:modelValue', fileList.value);
  } else {
    // 在文件列中取出失败的文件
    if (!fileList?.value?.length) return;
    fileList.value.forEach((item, i) => {
      if (item.uid === file.uid) fileList.value.splice(i, 1);
    });
  }
}

// 关闭查看器
function closeViewer() {
  dialogVisible.value = false;
}
</script>
<style lang="scss" scoped>
.uploadImage {
  > div {
    display: flex;
    align-items: flex-end;
  }
  :deep() {
    .el-upload--picture-card {
      width: 100px;
      height: 100px;
    }
    .el-upload-list--picture-card .el-upload-list__item {
      width: 100px;
      height: 100px;
    }
  }
}

.img_dialog :deep(.el-dialog__headerbtn) {
  top: -12px;
}

.picture_dialog {
  width: fit-content;
}

.upload_tip {
  color: #909399;
}
</style>
